(function(window) {
// {url, dir}
var FileUpload = function(id, opt){ return new FileUpload.prototype.init(id, opt);}
FileUpload.prototype = {
	uploading: function(){
		var ot = this;
        this.cont.find('form').attr('action', ROOT_URL + (this.url || '?u=cfile\\a-fupload')+  '&dir='+this.dir+'&baseDir='+this.bDir )
				.submit(function(e){
					e.stopPropagation();
					ot.cont.addClass('ajax-loading');
				}).submit();
	},
    uploaded: function(res){
		this.cont.removeClass('ajax-loading');
        if (checAjaxRe(res)){
			if (typeof this.callFun =='function')
                this.callFun(res);
			else{
                if (this.hand[0].nodeName =='input' ||this.hand[0].nodeName =='INPUT')
                    this.hand.val(res.path);
			}
		}
    }
}
FileUpload.prototype.init = function(id, opt){
	var ot = this;
	ot.hand = $(id);
	ot.dir = "";
    ot.isAutoUpload = true;
    ot.callFun = null;
	if (typeof opt=="object")
		for(var i in opt)
			ot[i] = opt[i];

    var sp = $('<span>');
    ot.cont = sp;
	if (this.hand[0].nodeName =='input' ||this.hand[0].nodeName =='INPUT')
        ot.hand.after(sp);
    else
        ot.hand.append(sp);
    
    var _n=Math.random(), str = '<span><form target="upifrme_'+_n+'" style="position:relative;padding:0; margin:0; border:0" method="post" enctype="multipart/form-data"><a class="upload-select p-browseBut">'+ language._('shang chuan wen jian') +'</a><input type="file" style="position:absolute;left:0;top:0;opacity:0;height:100%;width:100%;" name="file" /></form><iframe style="display:none" name="upifrme_'+_n+'"></iframe></span>';
    sp.append(str);
    sp.find('iframe').load(function(){
        var o = $(this), s = o.contents().find('body').text(),res;
        if (o[0].contentWindow.document.location.href=='about:blank')return;
		try { res = $.parseJSON(s);}
		catch (err) { res = s ;}
        ot.uploaded(res);
    });
    sp.find('input:first').bind('change',function(){
        if(ot.isAutoUpload)ot.uploading();
    });
    
	return this;
};
// global
FileUpload.prototype.init.prototype = FileUpload.prototype;
window.FileUpload = FileUpload;
})(window);
